<?php


namespace app\user\controller;


use app\superadmin\model\User;
use think\Controller;
use think\Db;
use think\facade\Request;
use think\facade\Session;

class Index extends Controller
{
    #region 界面
    public function index()
    {
        $Token = Session::get('Token');
        if ($Token != null && $Token != '') {
            $User = new User();
            $UserData = $User->mb_Get("Token='$Token'");
            if ($UserData != null && $UserData->Level == 2 && $UserData->IsDeleted == 0) {
                header("Location: /index.php/user/home");
                exit();
            }
        }
        return $this->fetch('login');
    }
    #endregion

    #region 接口

    /**
     * 登錄
     */
    public function mb_Login()
    {

        $Name = Request::has('Name') ? addslashes(Request::param('Name')) : '';
        $Pass = Request::has('Pass') ? addslashes(Request::param('Pass')) : '';
        $EncPass = md5($Pass);

        $User = new User();
        $UserData = $User->mb_Get("Name='$Name' AND EncPass='$EncPass' AND IsDeleted='0'");
        if ($UserData == null) {
            mb_OutMessage(ErrCode_Toast, '账号或密码有误！');
        }
        if ($UserData['Level'] != Level_CRMUser) {
            mb_OutMessage(ErrCode_Toast, '账号或密码有误！');
        }

        Db::startTrans();
        try {
            $Token = md5($UserData->Name . time());
//            $Token = $UserData->Token;
//            $UserData->Name = $UserData->Name;
            $UserData->Token = $Token;
            $UserData->save();
            Db::commit();
            Session::set('Token', $Token);
            mb_OutMessage(ErrCode_Normal, '登入成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    public function mb_Logout()
    {
        $Token = Session::get('Token');
        if($Token == ''){
            header("Location: /index.php/user/");
            exit();
        }
        $User = new User();
        $UserData = $User->mb_Get("Token='$Token'");

        if ($UserData == null || $UserData->Level != 1 || $UserData->IsDeleted != 0) {
            Session::delete('Token');
            header("Location: /index.php/user/");
            exit();
        }
        Db::startTrans();
        try {
            $UserData->Token = '';
            $UserData->save();
            Session::delete('Token');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return;
        }
        $this->success('登出成功','/index.php/user/');
    }
    #endregion
}